import { AbsFormUtil } from '@abstract/form';
import { Component, OnInit } from '@angular/core';
import { VisitService } from '@service/visit.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder } from '@angular/forms';
import { IVisitTheme } from '@model/visit';
import { deepClone } from '@utils/lang';
import { AuthService } from '@service/auth.service';
const ID = '123456789';

@Component({
	selector: 'app-visit-theme',
	templateUrl: './visit-theme.component.html',
	styleUrls: ['./visit-theme.component.less']
})
export class VisitThemeComponent extends AbsFormUtil implements OnInit {
	nzLoading = false;
	data = [];
	editData: IVisitTheme = null;
	
	constructor(
		private visitService: VisitService,
		private nzMessageService: NzMessageService,
		private fb: FormBuilder,
		private authService: AuthService

	) {
		super();
		this.authList = this.authService.getAuth();
	}

	ngOnInit() {
		this.buildForm();
		this.onSearch();
		

	}
	buildForm() {
		this.validateForm = this.fb.group({
			visitTitle: [null]
		});
	}
	
	async onSearch(isPageInit?: boolean) {
		this.nzLoading = true;
		if (isPageInit) {
			this.page.page = 1;
		}
 		const params = {...this.validateForm.value, ...this.page};
		const result = await this.visitService.getVisitTheme(params);
		this.nzLoading = false;

		this.data = result.data.list;
		this.page.total = result.data.totalCount;

	}



	create() {
		if (this.editData && this.editData.id) {
			this.nzMessageService.info('请一次编辑一条数据');
			return;
		}
		this.editData = new IVisitTheme();
		this.editData.id = ID;
		this.data.unshift(this.editData);
		this.data = [...this.data];
	}
	async del(item) {
		await this.visitService.deleteVisitTheme(item.id);
		this.nzMessageService.success('删除成功');
		this.onSearch(true);
	}
	cancel() {
		if (this.editData.id === ID) {
			this.data.shift();
			this.data = [...this.data];
		}
		this.editData = null;
	}
	edit(item: IVisitTheme) {
		if (this.editData && this.editData.id) {
			this.nzMessageService.info('请一次编辑一条数据');
			return;
		}
		this.editData = deepClone(item);
	}

	async save(item: IVisitTheme) {
		const editData = JSON.parse(JSON.stringify(this.editData));
		const isCreate = editData.id === ID;
		if (isCreate) {
			editData.id = null;
		}
		const result = await this.visitService.saveVisitTheme(editData) 
		if (result.status !== 0) {
			this.nzMessageService.error(result.msg);
			return;
		}
		isCreate ? this.onSearch(true) : Object.assign(item, editData);
		this.editData = new IVisitTheme();
		this.nzMessageService.success(isCreate ? '新增成功' : '修改成功');
	}
}
